package com.spica.platform.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.spica.platform.base.model.SysMenu;
import com.spica.platform.common.constant.CommonConstant;
import com.spica.platform.db.service.impl.ServiceImpl;
import com.spica.platform.user.mapper.SysMenuMapper;
import com.spica.platform.user.model.SysRoleMenu;
import com.spica.platform.user.service.ISysMenuService;
import com.spica.platform.user.service.ISysRoleMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

	@Resource
	private ISysRoleMenuService roleMenuService;


	/**
	 * 角色菜单列表
	 *
	 * @param roleIds 角色id
	 * @return 角色id对应的菜单列表
	 */
	@Override
	public List<SysMenu> findSysMenuByRoleIds(Set<Long> roleIds) {
		return roleMenuService.findSysMenusByRoleIds(roleIds, null);
	}

	/**
	 * 角色菜单列表
	 *
	 * @param roleCodes 角色代码
	 * @return 角色代码对应的菜单列表
	 */
	@Override
	public List<SysMenu> findSysMenuByRoleCodes(Set<String> roleCodes, Integer type) {
		return roleMenuService.findSysMenusByRoleCodes(roleCodes, type);
	}

	/**
	 * 角色和菜单建立关系,保存在role_menu表
	 * @param roleId 角色id
	 * @param menuIds 菜单id
	 * @return 是否操作成功
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public boolean setMenuToRole(Long roleId, Set<Long> menuIds) {
		boolean flag = false;
		if (!CollectionUtils.isEmpty(menuIds)) {
			roleMenuService.remove(roleId, null) ;
			List<SysRoleMenu> roleMenus = new ArrayList<>(menuIds.size());
			menuIds.forEach(menuId -> roleMenus.add(SysRoleMenu.builder().roleId(roleId).menuId(menuId).build()));
			flag = roleMenuService.saveBatch(roleMenus);
		}
		return flag;
	}

	/**
	 * 查询所有一级菜单
	 */
	@Override
	public List<SysMenu> findOnes() {
		return baseMapper.selectList(Wrappers.<SysMenu>lambdaQuery().eq(SysMenu::getType, CommonConstant.MENU).orderByAsc(SysMenu::getSort));
	}

}
